# -*- coding: utf-8 -*
__author__ = 'dell'
import copy
import csv
input = open('newCycleTime.txt', 'r')

F=[]
tempF=[]
n=1
for eachline in input.readlines():
    temp1 = eachline.strip().split('\t')
    tempF.append(temp1)
    if n%4==0:
        F.append(tempF)
        tempF=[]
    n +=1

AcycleSet = {}

for eachF in F:
    if eachF[0][0] in AcycleSet:
        AcycleSet[eachF[0][0]].append(eachF)
    else:
        AcycleSet[eachF[0][0]] = []
        AcycleSet[eachF[0][0]].append(eachF)

keySet = []
def getType(name):
    namelist = list(name)
    return namelist[0]

def modifyEachF(advanValue,modifyingF):#含有S的时间定环，起点时间不为0
    modifyPoint = 0
    for i in range(len(modifyingF[0])):
        if getType(modifyingF[0][i])=='S':
            modifyPoint = i
            break
    for j in range(2*modifyPoint):
        modifyingF[-1][j] =int(modifyingF[-1][j])-advanValue
    return modifyingF
#####################

def addEachF(advanValue,addingF):#不含外卖订单的时间可调环，起点时间为0
    for j in range(len(addingF[-1])):
        addingF[-1][j] =int(addingF[-1][j])+advanValue
    return addingF
######################

m=0
newF=[]
def dealstartIsNot0IsNull(startIs0):
    reverseStartIs0 = sorted(startIs0,reverse=True)
    while len(reverseStartIs0)>0:
        newCycle =0
        deleteList = []
        timeLimit = 0
        for i in range(0,len(reverseStartIs0)):
            if i==0:
                newCycle =copy.deepcopy(reverseStartIs0[i][1])
                deleteList.append(reverseStartIs0[i])
                timeLimit = reverseStartIs0[i][0]
            else:
                if timeLimit+int(reverseStartIs0[i][1][-1][-2])<=720:
                    deleteList.append(reverseStartIs0[i])
                    newCycle[0] += reverseStartIs0[i][1][0][1:]
                    newCycle[1] += reverseStartIs0[i][1][1][1:]
                    newCycle[2].pop()
                    newCycle[2] +=reverseStartIs0[i][1][2][:]
                    newCycle[3] += [int(x)+timeLimit for x in reverseStartIs0[i][1][3][:]]
                    timeLimit +=reverseStartIs0[i][0]
                else:pass
        for k in deleteList:
            reverseStartIs0.remove(k)
        newCycle[0].pop()
        newCycle[1].pop()
        newCycle[2].pop()
        newCycle[3].pop()
        newF.append(newCycle)

for key,value in AcycleSet.items():
    startIs0 = []
    startIsNot0 = [] #有些A是没有外卖订单的
    for eachone in value:
        #print eachone
        if int(eachone[-1][0])==0:
            startIs0.append([int(eachone[-1][-1]),eachone])
        else:
            startIsNot0.append([int(eachone[-1][0]),int(eachone[-1][-1]),eachone])
    if startIsNot0 ==[]:
        dealstartIsNot0IsNull(startIs0)
    else:
        sortStartIs0 =sorted(startIs0,reverse=True)
        sortStartIsNot0 =sorted(startIsNot0)
        while len(sortStartIsNot0)>0:
            newCycle =0
            StartIsNot0deleteList = []
            timeLimitLeft = 0
            timeLimitRight = 0
            #######  1、排时间定环，根据时间接续时间定环，每接续一个，往中间补若干时间不定环
            #######  2、剔除所补的时间不定环，在当前环的前面和后面补若干时间不定环
            #######  3、剔除使用的时间定环和所补的时间不定环，添加该环信息
            for i in range(len(sortStartIsNot0)):
                if i==0:
                    newCycle =copy.deepcopy(sortStartIsNot0[i][2])
                    timeLimitLeft = sortStartIsNot0[i][0]
                    timeLimitRight = sortStartIsNot0[i][1]
                    StartIsNot0deleteList.append(sortStartIsNot0[i])
                else:
                    if sortStartIsNot0[i][0]>=timeLimitRight:
                        dt = sortStartIsNot0[i][0]-timeLimitRight #用于时间不定环补空
                        StartIs0deleteList = []
                        for j in range(len(sortStartIs0)):
                            if sortStartIs0[j][0]<=dt:
                                StartIs0deleteList.append(sortStartIs0[j])
                                timeLimitRight += sortStartIs0[j][0]
                                dt = dt -sortStartIs0[j][0]
                                advanValue = int(newCycle[3][-1])
                                temp = copy.deepcopy(sortStartIs0[j][1])
                                temp = addEachF(advanValue,temp)
                                newCycle[0].pop()
                                newCycle[1].pop()
                                newCycle[2].pop()
                                newCycle[0] +=temp[0][:]
                                newCycle[1] +=temp[1][:]
                                newCycle[2] +=temp[2][:]
                                newCycle[3] +=temp[3][:]
                            else:pass
                        for k in StartIs0deleteList:
                            sortStartIs0.remove(k)
                        temp2 = copy.deepcopy(sortStartIsNot0[i][2])
                        temp2 = modifyEachF(dt,temp2)
                        timeLimitRight = sortStartIsNot0[i][1]
                        StartIsNot0deleteList.append(sortStartIsNot0[i])
                        newCycle[0].pop()
                        newCycle[1].pop()
                        newCycle[2].pop()
                        newCycle[0] +=temp2[0][:]
                        newCycle[1] +=temp2[1][:]
                        newCycle[2] +=temp2[2][:]
                        newCycle[3] +=temp2[3][:]
            for m in StartIsNot0deleteList:
                sortStartIsNot0.remove(m)

            StartIs0deleteList2 = []
            for j in range(len(sortStartIs0)):
                if sortStartIs0[j][0]<=720-timeLimitRight:
                    StartIs0deleteList2.append(sortStartIs0[j])
                    timeLimitRight += sortStartIs0[j][0]
                    advanValue = int(newCycle[3][-1])
                    temp3 = copy.deepcopy(sortStartIs0[j][1])
                    temp3 = addEachF(advanValue,temp3)
                    newCycle[0].pop()
                    newCycle[1].pop()
                    newCycle[2].pop()
                    newCycle[0] +=temp3[0][:]
                    newCycle[1] +=temp3[1][:]
                    newCycle[2] +=temp3[2][:]
                    newCycle[3] +=temp3[3][:]
                else:pass
            for k in StartIs0deleteList2:
                sortStartIs0.remove(k)

            StartIs0deleteList3 = []
            for j in range(len(sortStartIs0)):
                if sortStartIs0[j][0]<=timeLimitLeft:
                    StartIs0deleteList3.append(sortStartIs0[j])
                    timeLimitLeft = timeLimitLeft-sortStartIs0[j][0]
                    temp4 = copy.deepcopy(sortStartIs0[j][1])
                    temp4 = addEachF(timeLimitLeft,temp4)
                    temp4[0].pop()
                    temp4[1].pop()
                    temp4[2].pop()
                    newCycle[0] =temp4[0][:]+newCycle[0]
                    newCycle[1] =temp4[1][:]+newCycle[1]
                    newCycle[2] =temp4[2][:]+newCycle[2]
                    newCycle[3] =temp4[3][:]+newCycle[3]
                else:pass
            for k in StartIs0deleteList3:
                sortStartIs0.remove(k)
            ad = int(newCycle[-1][0])
            newCycle = modifyEachF(ad,newCycle)
            newCycle[0].pop()
            newCycle[1].pop()
            newCycle[2].pop()
            newCycle[3].pop()
            newF.append(newCycle)


        if len(sortStartIs0)>0:#处理剩余的时间不定环
            dealstartIsNot0IsNull(sortStartIs0)

cutDistance =16
newnewF=[]
######以while的形式,往newnewF中添加，不切割就直接添加，若切割，则切割后添加
while len(newF)>0:
    cutPointList=[]
    for j in range(1,len(newF[0][0])):
        if getType(newF[0][0][j])=='A' and int(newF[0][-1][2*j-1])-int(newF[0][-1][2*j-2])>cutDistance:
            cutPointList.append(j)

    if cutPointList==[]:
        newnewF.append(copy.deepcopy(newF[0]))
        newF.pop(0)
    else:

        newnewF.append([newF[0][0][0:cutPointList[0]],newF[0][1][0:cutPointList[0]],newF[0][2][0:cutPointList[0]],newF[0][3][0:2*cutPointList[0]-1]])

        for i in range(0,len(cutPointList)):
            if i ==len(cutPointList)-1:
                time = int(newF[0][3][2*cutPointList[i]-1])
                newnewF.append([newF[0][0][cutPointList[i]:],newF[0][1][cutPointList[i]:],newF[0][2][cutPointList[i]:],newF[0][3][2*cutPointList[i]:]])
                demo = []
                for eacha in newnewF[-1][0]:
                    demo.append(getType(eacha))
                if 'S' in demo:newnewF[-1]=modifyEachF(time,newnewF[-1])[:]
                else:
                    for j in range(len(newnewF[-1][-1])):
                        newnewF[-1][-1][j] = int(newnewF[-1][-1][j])-time
            else:
                newnewF.append([newF[0][0][cutPointList[i]:cutPointList[i+1]],newF[0][1][cutPointList[i]:cutPointList[i+1]],newF[0][2][cutPointList[i]:cutPointList[i+1]],newF[0][3][2*cutPointList[i]:2*cutPointList[i+1]-1]])
                time = int(newF[0][3][2*cutPointList[i]-1])
                demo = []
                for eacha in newnewF[-1][0]:
                    demo.append(getType(eacha))
                if 'S' in demo:newnewF[-1]=modifyEachF(time,newnewF[-1])
                else:
                    for j in range(len(newnewF[-1][-1])):
                        newnewF[-1][-1][j] = int(newnewF[-1][-1][j])-time


        newF.pop(0)



print len(newnewF)





################################################################
outputF = open('FinalCycleTime.txt', 'w') #新的环路
for eachF in newnewF:
    for subeachF in eachF:
        for subsubeachF in subeachF:
            outputF.write('%s\t' %subsubeachF)
        outputF.write('\n')

input.close()
outputF.close()


NoInput = open('6.txt', 'r')
NoSet = []
for eachline in NoInput.readlines():
    NoSet.append(eachline.strip().split()[0])
NoInput.close()

finalRessult = []

for i in range(len(newnewF)):
    line0 =newnewF[i][0][:]
    line1 =newnewF[i][1][:]
    line2 =newnewF[i][2][:]
    line3 =newnewF[i][3][:]
    Atimeleft = 0
    Atimeright = 0
    Aname = line1[0]
    Aset = []
    noAset=[]
    for j in range(1,len(line1)):
        if getType(line1[j])=='A':
            finalRessult = finalRessult + Aset[:]
            finalRessult = finalRessult + noAset[:]
            Atimeleft = line3[2*j-1]
            Atimeright = line3[2*j]
            Aname = line1[j]
            Aset = []
            noAset=[]
        elif getType(line1[j])=='F':
            Aset.append([NoSet[i],Aname,Atimeleft,Atimeright,-int(line2[j]),line1[j]])
            noAset.append([NoSet[i],line0[j],line3[2*j-1],line3[2*j],line2[j],line1[j]])
        elif getType(line1[j])=='E':
            noAset.append([NoSet[i],line0[j],line3[2*j-1],line3[2*j],line2[j],line1[j]])
    if Aset==[]:
        finalRessult = finalRessult + noAset[:]
    else:
        finalRessult = finalRessult + Aset[:]
        finalRessult = finalRessult + noAset[:]


with open('FinalResult.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile,dialect='excel')
    for eachResult in finalRessult:
        spamwriter.writerow(eachResult)

print len(newF)
